<script setup>
import { updateUserAvatarApi } from "@/api/user";
import { ElMessage } from "element-plus";
import { ref } from "vue";
import useUserStore from "@/stores/user";
const userStore = useUserStore();

const iptFile = ref(null);
const avatar = ref(null);

const chooseImg = () => {
  iptFile.value.click();
};
const onFileChange = (e) => {
  if (e.target.files.length === 0) return;
  //   console.log(e.target.files[0]); //图片对象 => 图片路径或base64图片编码

  // 头像选择完毕后进行预览 FileReader(文件读取器)
  const reader = new FileReader();
  reader.readAsDataURL(e.target.files[0]); //读文件异步
  reader.onload = () => {
    // console.log(reader.result);
    avatar.value = reader.result;
  };
};

const uploadImg = async () => {
  const { data: res } = await updateUserAvatarApi({ avatar: avatar.value });
  if (res.code !== 0) return ElMessage.error(res.message);
  ElMessage.success(res.message);
  userStore.getUserInfo();
};
</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>用户头像</span>
      </div>
    </template>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar" alt="" v-if="avatar" class="preview" />
      <img src="@/assets/images/avatar.jpg" alt="" v-else />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          type="file"
          accept="image/*"
          style="display: none"
          ref="iptFile"
          @change="onFileChange"
        />
        <el-button type="primary" @click="chooseImg">选择图片</el-button>
        <el-button type="success" :disabled="avatar === null" @click="uploadImg"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<style scoped lang="less">
.btn-box {
  margin-top: 10px;
}

.preview {
  width: 400px;
  height: 300px;
  object-fit: cover;
}
</style>
